<?php
session_start();
$asset_title ='';
$abstract ='';
$lectureDate ='';
$duration ='';
$asset_type ='';
$remoteURL= '';
$location= '';
$eventTitle= '';
$abstract_url ='';
$rating='';
$views='';
$thumbnail ='';
$institute_id = $_SESSION['institute_id'];
$user_id= $_SESSION['user_id'];
//echo "institute_id=$institute_id<bR>";
//$timecode_sha1='';
$thumbnail_type ='';
if($asset_id !='')
{
 	$asset_id= $_REQUEST['asset_id'];
	$sqltext="select title as asset_title, 
										abstract, 
										to_char(asset.lecture_date,'mm/dd/yyyy') as lecture_date,  
										to_char(asset.lecture_date,'HH24:MI:SS') as lecture_time,  
										duration, 
										asset_type as type, 
										abstract_url, 
										remote_url, 
										location, 
										event_title, 
										rating, 
										views,
										thumbnail_type,
										asset_type
										from asset WHERE id=?";
	$params = array();	
	array_push($params,sql_escape($asset_id));
	$result = db_select_query($conn,$sqltext,$params);
	while($row = db_fetch_object($result))
	{
		foreach ($row as $key => $value) 
		{
			$value = trim($value);
			$$key = $value;
			//echo "$$key = $value<bR>";
			if($key=='duration')
			{
				$duration = (int)$duration/60;
			}
		}		
		
	}
}
if($asset_id !=''  && isset($_POST['edit']) && $_POST['edit'] !='')//edit asset
{
	 
	$asset_title = $_POST['title'];
	$lectureDate = $_POST['lecture_date'];
	$abstract = $_POST['abstract'];
	$duration = $_POST['duration'];
	$asset_type = $_POST['type'];
	$remoteURL = $_POST['remote_url'];
	$location = $_POST['location'];
	$eventTitle = $_POST['event_title'];
	$rating = $_POST['rating'];
	$views = $_POST['views'];
	$abstract_url = $_POST['abstract_url'];
	
	$lectureDate = $_POST['lecture_date'];
	$lecture_time = $_POST['lecture_time'];
	//echo $abstract."<br>";
	//echo $lectureDate."<br>";
	//echo $lecture_time."<br>";
	if($lecture_time  !='')
	{
		$lecture_time =$lecture_time .":00";
	}
	$insert_date =date('Y-m-d',strtotime($lectureDate)).' '.$lecture_time;
//	echo date('Y-m-d',strtotime($lectureDate)).' '.$lecture_time."<br>";
	/*   echo $asset_title ."<br>";
	 echo $lectureDate."<br>";
	 echo $abstract ."<br>";
	 echo $duration ."<br>";
	 echo $asset_type."<br>";
	 echo $remoteURL ."<br>";
	 echo $location ."<br>";
	 echo $eventTitle."<br>";
	 echo $rating."<br>";
	 echo $views ."<br>";
	 echo $abstract_url ."<br>";*/
	$error_message ='';
	if(!isset($asset_title) ||  $asset_title=='')
	{
		$error_message .= "missing required field - title\\r\\n";
	}
	if(!isset($lectureDate) ||  $lectureDate=='')
	{
	 $error_message .= "missing required field - lecture Date\\r\\n";
	}
	if(!isset($remoteURL) ||  $remoteURL=='')
	{
	 $error_message .= "missing required field - remote URL\\r\\n";
	}
	if(!isset($location)||  $location=='' )
	{
	 $error_message .= "missing required field - location\\r\\n";
	}
	
	if($error_message  =='')
	{
		
		$lectureDate =strtotime($insert_date);
		//*************get other informatin for asset checksum update*******/
	  $sqltext="select first_name,last_name,middle_name, alt_name,suffix, department,title, organization as company,id
										from presenter WHERE asset_id=? 
											order by last_name,first_name,middle_name,suffix,alt_name,title,department,company";
		$params = array();	
		array_push($params,sql_escape($asset_id));
		$result = db_select_query($conn,$sqltext,$params);	
		unset($presenters_list);
		$presenter_checksum ='';
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				$$key = $value;
			}	
			$presenters_list[] = $last_name.$first_name.$middle_name.$suffix.$alt_name.$title.$department.$company;		
		}	
		if(isset($presenters_list) )
		{
			sort($presenters_list);
			for($i=0;$i<count($presenters_list); $i++)
			{
				$presenter_checksum .= $presenters_list[$i];
			}
		}
		//ms array, and keyword array
		$sqltext="SELECT msc FROM msc_number  WHERE asset_id= ? order by msc";
		$params = array();
		array_push($params,sql_escape($asset_id));
		$result = db_select_query($conn,$sqltext,$params);
		unset($msc_array);	
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				$msc_array[]=$value;
			}
		}
		$sqltext="SELECT keyword FROM keyword  WHERE asset_id=?  order by keyword";
		$params = array();
		array_push($params,sql_escape($asset_id));
		$result = db_select_query($conn,$sqltext,$params);
		unset($keyword_array);
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				$keyword_array[]=$value;
			}
		}
		
		$lectureDate = strtotime($lecture_date);
		$msc_list ='';
		if(isset($msc_array))
		{
			for($i=0;$i<count($msc_array); $i++)
			{
				$msc_list .= $msc_array[$i];
			}
			
		}
		$keywords_list ='';
		if(isset($keyword_array))
		{
			for($i=0;$i<count($keyword_array); $i++)
			{
				$keywords_list .= $keyword_array[$i];
			}
			
		}
		$asset_string =$asset_title.$abstract.$lectureDate.$duration.$type.$remoteURL.$location.$eventTitle.$msc_list.$keywords_list.$presenter_checksum;
		
	
	//	$asset_string =$asset_title.$abstract.$lectureDate.$duration.$type.$remoteURL.$location.$eventTitle;
		//echo date("Y-m-d H:i:s",$lectureDate);
		//echo $asset_string."<br>";
		//exit();
		$asset_sha1 = sha1($asset_string);
		//echo $asset_sha1."<br>";
	/*	$statistics_sha1 ='';
		if($rating!='' || $views!='')
		{
			$statistics_sha1 = sha1($rating.$views);
		}*/
		
		$thumbnail_sha1 ='';
		$saved_image ='';
		$file_type ='';
		$file = basename( $_FILES['upload_image']['name']);
		if($file != '')
		{
			$path_parts = pathinfo($file);
			$file_type  = $path_parts['extension'];
			
			$handle = fopen($_FILES["upload_image"]["tmp_name"], "r");
			$imgbinary = fread($handle, filesize($_FILES["upload_image"]["tmp_name"]));
			$encoded = strtr(base64_encode(addslashes(gzcompress(serialize($imgbinary),9))), '+/=', '-_,');
      $string= unserialize(gzuncompress(stripslashes(base64_decode(strtr($encoded, '-_,', '+/=')))));
			$thumbnail_sha1 = sha1($string.$file_type);
		//	echo "thumbnail:$string<bR>";
		}				
	//update asset table 
		$params = array();
		$sqltext="UPDATE asset SET ";
		$sqltext .="title =?,";
		array_push($params,sql_escape($asset_title));
		$sqltext .="abstract =?,";
		array_push($params,sql_escape($abstract));
		$sqltext .="lecture_date =?,";
		array_push($params,date("Y-m-d H:i:s",strtotime($insert_date)));
		if(isset($duration) && $duration !='')
		{
			$sqltext .="duration =?,";
			array_push($params,sql_escape($duration*60));
		}
		else
		{
			 $sqltext .="duration =?,";
			 array_push($params,0);
		}
		$sqltext .="asset_type =?,";
		array_push($params,sql_escape($asset_type));
		$sqltext .="remote_url =?,";
		array_push($params,sql_escape($remoteURL));
		$sqltext .="location =?,";
		array_push($params,sql_escape($location));
		$sqltext .="event_title =?,";
		array_push($params,sql_escape($eventTitle));
		$sqltext .="last_modified_datetime =?,";
		array_push($params,date("Y-m-d H:i:s"));
		$sqltext .="last_modified_by =?";
		array_push($params,sql_escape($user_id));
		if(isset($rating) && $rating !='')
		{
			$sqltext .=",rating =?";
			array_push($params,sql_escape($rating));
		}
		else
		{
			 $sqltext .=",rating =?";
			array_push($params,0);
		}
		if(isset($views) && $views !='')
		{
			$sqltext .=",views =?";
			array_push($params,sql_escape($views));
		}
		else
		{
			 $sqltext .=",views =?";
			array_push($params,0);
		}
		$statistics_sha1 ='';
		if($rating!='' || $views!='')
		{
			$statistics_sha1 = sha1($rating.$views);
			$sqltext .=",statisticsSHA1 =?";
	  	array_push($params,sql_escape($statistics_sha1));
		}
		$sqltext .=",assetSHA1 =?";
		array_push($params,sql_escape($asset_sha1));
				
		if($file != '')
		{		
			$sqltext .=",thumbnailSHA1 =?";
			array_push($params,sql_escape($thumbnail_sha1));
			$sqltext .=",thumbnail_type =?";
			array_push($params,sql_escape($file_type));			
	
		}
		/*else
		{
			$sqltext .=",thumbnail_type =?";
			array_push($params,sql_escape(''));
		}*/
		$sqltext .=" WHERE id=?";
		array_push($params,sql_escape($asset_id));
		db_change_query($conn,$sqltext,$params);
	 //update thumbnail
		if($file != '')
		{	
			if(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id"))
			{
				mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id", 0777); 
				mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$asset_id", 0777); 
			}
			elseif(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$asset_id"))
			{
				mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$asset_id", 0777); 
			}
			$target = $_SERVER['DOCUMENT_ROOT'] . '/math-videos/images/'.$institute_id.'/'. $asset_id."/";
			if($thumbnail_type !='')
			{
				$image_name =$asset_id."_thumb.".$thumbnail_type;
				if(file_exists($target.$image_name))
				{
					unlink($target.$image_name);
				}
			}
			$saved_image = $asset_id.'_thumb.'.$file_type;
		//	echo $target.$saved_image."<bR>";
			if(!move_uploaded_file($_FILES["upload_image"]["tmp_name"],$target.$saved_image)) 
			{
				 echo "<div  style='color:red;' align='center'> Sorry, there was a problem uploading your file.</div>";
			}
			chmod($target.$saved_image, 0755);
		}
		
	}
	else
	{
		$alert_message = $error_message;
	}

}
if(isset($_POST['save']) && $_POST['save'] !='')//add new asset
{
	$asset_title = $_POST['title'];
	$lectureDate = $_POST['lecture_date'];
	$abstract = $_POST['abstract'];
	$duration = $_POST['duration'];
	$asset_type = $_POST['type'];
	$remoteURL = $_POST['remote_url'];
	$location = $_POST['location'];
	$eventTitle = $_POST['event_title'];
	$rating = $_POST['rating'];
	$views = $_POST['views'];
	$abstract_url = $_POST['abstract_url'];
	$lecture_date = $lectureDate;
	$remote_url = $remoteURL;
	$event_title = $eventTitle;
	$lecture_time = $_POST['lecture_time'];
	if($lecture_time  !='')
	{
		$lecture_time =$lecture_time .":00";
	}
	$insert_date =date('Y-m-d',strtotime($lectureDate)).' '.$lecture_time;
	$lectureDate = strtotime($insert_date);
	/*   echo $asset_title ."<br>";
	 echo $lectureDate."<br>";
	 echo $abstract ."<br>";
	 echo $duration ."<br>";
	 echo $asset_type."<br>";
	 echo $remoteURL ."<br>";
	 echo $location ."<br>";
	 echo $eventTitle."<br>";
	 echo $rating."<br>";
	 echo $views ."<br>";
	 echo $abstract_url ."<br>";*/
	$error_message ='';
	if(!isset($asset_title) ||  $asset_title=='')
	{
		$error_message .= "missing required field - title";
	}
	if(!isset($lectureDate) ||  $lectureDate=='')
	{
	 $error_message .= "missing required field - lectureDate";
	}
	if(!isset($remoteURL) ||  $remoteURL=='')
	{
	 $error_message .= "missing required field - remoteURL";
	}
	if(!isset($location)||  $location=='' )
	{
	 $error_message .= "missing required field - location";
	}
	
	if($error_message  =='')
	{
		
		$asset_string =$asset_title.$abstract.$lectureDate.$duration.$type.$remoteURL.$location.$eventTitle;
		//echo date("Y-m-d H:i:s",$lectureDate);
		//echo $asset_string."<br>";
		//exit();
		$asset_sha1 = sha1($asset_string);
		$statistics_sha1 ='';
		if($rating!='' || $views!='')
		{
			$statistics_sha1 = sha1($rating.$views);
		}
		
		$thumbnail_sha1 ='';
		$saved_image ='';
		$file_type ='';
		$file = basename( $_FILES['upload_image']['name']);
		//	echo "file:".$_FILES['upload_image']['name']."<bR>";
		//$file_type = $_FILES['upload_file']['type'];
	//	$file_size = $_FILES['upload_image']['size'];
		/*if($file_size > $file_size_max)
		{
			$error_message .= "Your file size is $file_size, the uploaded file size can't over 10MB! " . $new_line_for_alert ;
			$alert_message = $error_message;
			 break;
		}*/
		if($file != '')
		{
			
			$path_parts = pathinfo($file);
			$file_type  = $path_parts['extension'];
			
			$handle = fopen($_FILES["upload_image"]["tmp_name"], "r");
			$imgbinary = fread($handle, filesize($_FILES["upload_image"]["tmp_name"]));
			$encoded = strtr(base64_encode(addslashes(gzcompress(serialize($imgbinary),9))), '+/=', '-_,');
      $string= unserialize(gzuncompress(stripslashes(base64_decode(strtr($encoded, '-_,', '+/=')))));
			$thumbnail_sha1 = sha1($string.$file_type);
		}			
			
	//insert to asset table 
 
	
		$sqltext="INSERT INTO asset(title, abstract, lecture_date, duration, asset_type, abstract_url, remote_url, location, event_title, created_datetime, created_by, last_modified_datetime, last_modified_by, rating, views, institute_id, assetSHA1,statisticsSHA1, thumbnailSHA1,thumbnail_type) values( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		$params = array();
		array_push($params,sql_escape($asset_title));
		array_push($params,sql_escape($abstract));
		//array_push($params,date("Y-m-d",strtotime($lectureDate)));
	//	array_push($params,date("Y-m-d H:i:s",strtotime($lectureDate)));
		array_push($params,date("Y-m-d H:i:s",strtotime($insert_date)));
		if($duration =='')
		{
			 array_push($params,sql_escape(0));
		}
		else
		{
			 array_push($params,sql_escape($duration*60));
		}
		
		array_push($params,sql_escape($asset_type));
		array_push($params,sql_escape($abstract_url));
		array_push($params,sql_escape($remoteURL));
		array_push($params,sql_escape($location));
		array_push($params,sql_escape($eventTitle));
		array_push($params,date("Y-m-d H:i:s"));
		array_push($params,sql_escape($user_id));
		array_push($params,date("Y-m-d H:i:s"));// insert record, modified_date_time = created_date_time
		array_push($params,sql_escape($user_id));
		if($rating =='')
		{
			 array_push($params,sql_escape(0));
		}
		else
		{
			 array_push($params,sql_escape($rating));
		}
		
		if($views =='')
		{
			 array_push($params,sql_escape(0));
		}
		else
		{
			 array_push($params,sql_escape($views));
		}
		
		array_push($params,sql_escape($institute_id));
		array_push($params,sql_escape($asset_sha1));
		//array_push($params,sql_escape($timecode_sha1));
		array_push($params,sql_escape($statistics_sha1));
		array_push($params,sql_escape($thumbnail_sha1));
		if(isset($file) && $file !='' )
		{			
			array_push($params,sql_escape($file_type));
		}
		else
		{
		//	array_push($params,'');
			array_push($params,'');
		}
		//print($sqltext);
	//	print_r($params);
		db_change_query($conn,$sqltext,$params);
		$sqltext = "SELECT id  as asset_id FROM asset ORDER BY id DESC LIMIT 1";
		$params = array();
    $result = db_select_query($conn,$sqltext,$params);
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				$$key= $value;
			}
		}
		//upload image
		if($file !='')
		{
			if(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id"))
			{
				mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id", 0777); 
				mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$asset_id", 0777); 
			}
			elseif(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$asset_id"))
			{
				mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$asset_id", 0777); 
			}
			$target = $_SERVER['DOCUMENT_ROOT'] . '/math-videos/images/'.$institute_id.'/'. $asset_id.'/';
			$saved_image = $asset_id.'_thumb.'.$file_type;
			$thumbnail_type = $file_type;
			/*if(!is_dir($target))
			{
				 mkdir($target, 0755, true);
			}
			 $target = $target."/";*/
			
			if(!move_uploaded_file($_FILES["upload_image"]["tmp_name"],$target.$saved_image)) 
			{
				 echo "<div  style='color:red;' align='center'> Sorry, there was a problem uploading your file.</div>";
			}
			 chmod($target.$saved_image, 0755);
			
		}
		
	}
	else
	{
		$alert_message = $error_message;
	}
}

$asset_area ="<input type='hidden' name='asset_id' value=\"$asset_id\" /><table>

<tr><td>Title:</td><td> <input type='text' name='title' value=\"$asset_title\" size='80'  maxlength='250' /></td></tr>
<tr><td valign='top'>Abstract:</td><td> <textarea  name='abstract' cols='60' rows='4' />$abstract</textarea></td></tr>
<tr><td>Lecture Date:</td><td> <input id=\"datepicker1\" type=\"text\" name=\"lecture_date\" value=\"$lecture_date\" /><select name='lecture_time'><option value=''>--Choose time--</option>";
for($t=0;$t<24; $t++)
{
	for($k=0; $k<=45; $k=$k+15)
	{
		$p = $k;
		if($p=='0')
		{
			$p='00';
		}
		if($t<10)
		{
			if($lecture_time == '0'.$t.':'.$p.':00')
			{
				$checked='SELECTED';
			}
			else
			{
				$checked='';
			}
			
		  $asset_area .="<option value='0".$t.":$p' $checked>0".$t.":$p</option>";
		}
		else
		{
				if($lecture_time == $t.':'.$p.':00')
			{
				$checked='SELECTED';
			}
			else
			{
				$checked='';
			}
			$asset_area .="<option value='".$t.":$p' $checked>".$t.":$p</option>";
		}
	}
}

$asset_area .="</select></td></tr>
<tr><td>Location:</td><td> <input type='text' name='location' value=\"$location\"  size='80'  maxlength='250' /></td></tr>
<tr><td>Event Title:</td><td> <input type='text' name='event_title' value=\"$event_title\"  size='80'  maxlength='250' /></td></tr>
<tr><td>Duration:</td><td> <input type='text' name='duration' value=\"$duration\"  size='10'  maxlength='80' />(mins)</td></tr>
<tr><td>Abstract URL:</td><td> <input type='text' name='abstract_url' value=\"$abstract_url\"  size='80'  maxlength='250' /></td></tr>
<tr><td>Type:</td><td> <input type='text' name='type' value=\"$asset_type\"  size='40'  maxlength='80' /></td></tr>

<tr><td>Remote URL:</td><td> <input type='text' name='remote_url' value=\"$remote_url\"  size='80'  maxlength='250' /></td></tr>

<tr><td>Rating:</td><td> <input type='text' name='rating' value=\"$rating\"  size='10'  maxlength='20' /></td></tr>
<tr><td>Views:</td><td> <input type='text' name='views' value=\"$views\"  size='10'  maxlength='20' /></td></tr>";
if($asset_id !='')
{
	 $asset_area .="<tr><td valign='top'>Image:</td><td>";
	 $asset_area .="<img src='../../images/".$institute_id."/".$asset_id."/".$asset_id."_thumb.".$thumbnail_type."' height='90' weight='100' /> <input  type=\"file\" name=\"upload_image\"  size='60' /></td></tr>";
}
else
{
	$asset_area .="<tr><td>Image:</td><td> <input  type=\"file\" name=\"upload_image\"  size='60' /></td></tr>";

}


$asset_area .="
<!--<tr><td>Presenters:</td><td> <img />+</td></tr>
<tr><td>First name:</td><td> <input type='text' name='given_name' value='' size='80'  maxlength='250' /></td></tr>
<tr><td>Last Name:</td><td> <input type='text' name='family_name' value='' size='80'  maxlength='250' /></td></tr>
<tr><td>Last Name:</td><td> <input type='text' name='family_name' value='' size='80'  maxlength='250' /></td></tr>
<tr><td>Title:</td><td> <input type='text' name='professor_title' value='' size='80'  maxlength='250' /></td></tr>
<tr><td>Company:</td><td> <input type='text' name='company' value='' size='80'  maxlength='250' /></td></tr>
-->
<!--<tr><td>Keywords:</td><td> <img />+</td></tr>
<tr><td>Keyword:</td><td> <input type='text' name='keywords' value='' size='80'  maxlength='250' /></td></tr>-->
";
if($asset_id !='')
{
	$asset_area .="<tr><td colspan='2' align='right'><input type='submit' name='edit' value='Save Changes'></td></tr>";
}
else
{
	 $asset_area .="<tr><td colspan='2' align='right'><input type='submit' name='save' value='Add Asset'></td></tr>";
}
	$asset_area .="
</table>";
?>